﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;
using Google.GData.Client;
using Google.GData.Documents;
using Google.GData.Extensions;
using Google.Documents;
using System.Windows.Forms;
using Google.GData.Apps;
using System.ComponentModel;
using System.Threading;
using System.Diagnostics;

namespace GDocUploader.Communication
{
    class Folder
    {
   
       
        private System.ComponentModel.BackgroundWorker DJ = new BackgroundWorker();

        private Stream Str;

        public bool fait = false; 

        public Folder(String chemin)
        {
            CreateFolder(new DirectoryInfo(chemin).Name);
            fait = true;
        }

        public Folder(String chemin, String PathTo)
        {
            string s = "";
            CreateFolder(new DirectoryInfo(chemin).Name, PathTo,out s);
            fait = true;
        }

        private String IdDocument = "";

   

        /// <summary>
        /// Crée un répertoire sous un compte Google 
        /// </summary>
        /// <param name="Name">Nom du répertoire</param>
        /// <returns>bool indiquant l'état de l'opération</returns>

        public Boolean CreateFolder(String Name)
        {
            Authentification.login();
            try
            {
                AtomCategory category = new AtomCategory("http://schemas.google.com/docs/2007#folder", new AtomUri("http://schemas.google.com/g/2005#kind"));
                category.Label = "folder";
                AtomEntry folder = new AtomEntry();
                folder.Categories.Add(category);
                folder.Title = new AtomTextConstruct(AtomTextConstructElementType.Title, Name);
                Uri feedUri = new Uri("http://docs.google.com/feeds/documents/private/full");
                Str = frmUploader.ServGen.EntrySend(feedUri, folder, GDataRequestType.Insert);
                Str.Close();
                Str.Dispose();
                clear();

              
                return true;
            }
            catch
            {
             

              
                return false;

            }
          
        }

        ///// <summary>
        ///// Crée un répertoire sous un compte Google 
        ///// </summary>
        ///// <param name="name">Nom du répertoire</param>
        ///// <param name="Id">Identificateur du répertoire parent</param>
        ///// <returns>bool indiquant l'état de l'opération</returns>
        //public Boolean CreateFolder(String name, String Id)
        //{
        //    try
        //    {
        //        AtomCategory category = new AtomCategory("http://schemas.google.com/docs/2007#folder", new AtomUri("http://schemas.google.com/g/2005#kind"));
        //        category.Label = "folder";
        //        AtomEntry folder = new AtomEntry();
        //        folder.Categories.Add(category);
        //        folder.Title = new AtomTextConstruct(AtomTextConstructElementType.Title, name);
        //        Uri feedUri = new Uri("http://docs.google.com/feeds/folders/private/full/folder%3A" + Id);
        //        Str = frmUploader.ServGen.EntrySend(feedUri, folder, GDataRequestType.Insert);
        //        Str.Close();
        //        Str.Dispose();
        //        if (!EventLog.SourceExists("GDOCUploader"))
        //            EventLog.CreateEventSource("GDOCUploader", "Application");
        //        EventLog.WriteEntry("GDOCUploader", "Fin de creation de " + name);

           
        //        return true;
        //    }
        //    catch(Exception ex)
        //    {
        //        if (!EventLog.SourceExists("GDOCUploader"))
        //            EventLog.CreateEventSource("GDOCUploader", "Application");
        //        EventLog.WriteEntry("GDOCUploader", "Erreur lors la creation de " + name + " detaille :" + ex.ToString());

             
        //        return false; }
        //}


        /// <summary>
        /// Crée un répertoire sous un compte Google 
        /// </summary>
        /// <param name="Name">Nom du répertoire</param>
        /// <param name="path_f">Path du repertoire sous Google</param>
        /// <param name="Message">Message d'erreur de sortie</param>
        /// <returns>bool indiquant l'état de l'opération</returns>
        public Boolean CreateFolder(String Name, String path_f, out String Message)
        {
            Authentification.login();
        finnn:
           DocumentsFeed F = null;
            try
            {
                if (path_f.EndsWith("/")) path_f = path_f.Remove(path_f.Length - 1);
                String[] Lst_Folder = path_f.Split('/');
                string parent = Lst_Folder[Lst_Folder.Length - 1];
               
               
                    try
                    {
                       F = GetDocs();
                        foreach (DocumentEntry d in F.Entries)
                        {
                            System.Windows.Forms.Application.DoEvents();
                            if (d.Title.Text == parent)
                            {
                                IdDocument = d.Content.Src.Content;
                                break;
                            }
                        }
                    }
                    catch
                    {
                        goto finnn;
                    }



                    //"http://docs.google.com/feeds/folders/private/full/folder%3A" + 
                AtomCategory category = new AtomCategory("http://schemas.google.com/docs/2007#folder", new AtomUri("http://schemas.google.com/g/2005#kind"));
                category.Label = "folder";
                AtomEntry folder = new AtomEntry();
                folder.Categories.Add(category);
                folder.Title = new AtomTextConstruct(AtomTextConstructElementType.Title, Name);
                Uri feedUri = new Uri(IdDocument);
                Str = frmUploader.ServGen.EntrySend(feedUri, folder, GDataRequestType.Insert);
                Str.Close();
                Str.Dispose();
             
                Message = IdDocument;
                clear();
                return true;
            }
            catch
            {
                Message = "";
                goto finnn;
            }
            


        }

        /// <summary>
        /// Obtient la list des documents
        /// </summary>
        /// <returns>List des DocumentEntry</returns>
        private DocumentsFeed GetDocs()
        {
            Authentification.login();
            DocumentsListQuery query = new DocumentsListQuery();
            query.ShowFolders = true;
            DocumentsFeed feed = frmUploader.ServGen.Query(query);
            return feed;
        }

        internal void clear()
        {
        finnnn:
            try
            {
                Authentification.login();
                DocumentsListQuery query = new DocumentsListQuery();
                query.ShowFolders = false;
                DocumentsFeed feed = frmUploader.ServGen.Query(query);
                foreach (DocumentEntry D in feed.Entries)
                {
                    if (D.Title.Text == "blank")
                    {
                        D.Delete();
                    }
                }
            }
            catch
            {
                goto finnnn;
            }

        }

    }
}
